/*
 * Copyright @ 苏州瑞云信息技术有限公司 All rights reserved.
 */
package cn.com.recloud.bbs.util;

import cn.com.recloud.one.spring.file.FileResult;
import cn.com.recloud.one.spring.file.FileService;
import cn.com.recloud.one.spring.file.FileStorageFactory;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

/**
 * @description 文件上传
 * @author Herry Hong
 * @date 2020/6/11
 */
@Component
public class FileUploadUtil {
    @Autowired
    private FileService fileService;

    /**
     * 单文件上传
     *
     * @param file 文件
     * @return
     */
    public String upload(MultipartFile file) {

        List<FileResult> fileResults = fileService.upload(ArrayUtils.toArray(file));
        if(CollectionUtils.isNotEmpty(fileResults)){
            FileResult fileResult = fileResults.get(0);
            return fileResult.getFileUrl();
        }
        return null;
    }

    /**
     * 多文件上传
     *
     * @param files
     * @return
     */
    public List<String> multiFileUpload(List<MultipartFile> files) {
        List<String> fileNameList = null;
        List<FileResult> fileResults = fileService.upload(files.toArray(new MultipartFile[0]));
        if(CollectionUtils.isNotEmpty(fileResults)){
            fileNameList = new ArrayList<>();
            for (FileResult fileResult : fileResults) {
                fileNameList.add(fileResult.getFileUrl());
            }
        }
        return fileNameList;
    }

}
